package x.ovo.wechat.bot;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import x.ovo.wechat.bot.common.command.Command;
import x.ovo.wechat.bot.common.command.CommandExecutor;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.plugin.Plugin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 关键字命令执行器
 *
 * @author ovo on 2024/05/14.
 * @since 1.0.0
 */
@Slf4j(topic = "关键字监控")
public class KeywordCommandExecutor extends CommandExecutor {

    protected KeywordCommandExecutor(Plugin plugin) {
        super(plugin);
    }

    @Override
    public void execute(Command command, TextMessage message) {
        try (Jedis jedis = KeywordListener.ds.getJedis()) {
            String fromName = command.getFromName();
            String[] args = command.formatArgs();
            String groupName = message.getFromUser().getNickName();

            if (!inAuthors(fromName)) {
                this.context.getApi().sendText(message.getFromUser().getUserName(), "你没有权限执行此命令，不要调皮");
                return;
            }

            if (!message.isGroup()) {
                this.context.getApi().sendText(message.getFromUser().getUserName(), "请在群聊中执行本指令");
                return;
            }

            try {
                if (args.length == 0 || args[0].equals("help")) {
                    this.context.getApi().sendText(message.getFromUser().getUserName(), help());
                } else if (args[0].equals("add")) {
                    this.context.getApi().sendText(message.getFromUser().getUserName(), add(groupName, jedis, args[1]));
                } else if (args[0].equals("remove")) {
                    this.context.getApi().sendText(message.getFromUser().getUserName(), remove(groupName, jedis, args[1]));
                } else if (args[0].equals("show")) {
                    this.context.getApi().sendText(message.getFromUser().getUserName(), show(groupName, jedis, args.length > 1 ? args[1] : null));
                }else {
                    this.context.getApi().sendText(message.getFromUser().getUserName(), "未知命令");
                }
            } catch (Exception e) {
                log.error("命令执行失败", e);
                this.context.getApi().sendText(message.getFromUser().getUserName(), "命令执行失败" + e.getMessage());
            }
        }
    }

    private String help() {
        return """
                [关键词监控]插件帮助：
                help                显示帮助
                add keyword...       添加需要监控的关键词
                remove keyword...    移除监控中的关键词
                show [keyword...]    显示关键词监控情况
                """;
    }

    private String add(String groupName,Jedis jedis, String... keys) {
        KeywordListener.KEYWORD_MAP.computeIfAbsent(groupName, k -> new ArrayList<>()).addAll(Arrays.asList(keys));
        jedis.hset(KeywordListener.KEYWORD_MAP_KEY, groupName, KeywordListener.KEYWORD_MAP.get(groupName).toString());
        log.info("添加 {} 成功", Arrays.toString(keys));
        return "添加 " + Arrays.toString(keys) + " 成功";
    }

    private String remove(String groupName,Jedis jedis, String... keys) {
        KeywordListener.KEYWORD_MAP.get(groupName).removeIf(s -> Arrays.asList(keys).contains(s));
        jedis.hset(KeywordListener.KEYWORD_MAP_KEY, groupName, KeywordListener.KEYWORD_MAP.get(groupName).toString());
        return "移除 " + Arrays.toString(keys) + " 成功";
    }

    private String show(String groupName,Jedis jedis, String... keys) {
        Map<String, String> map  = new HashMap<>(16);
        String redisKey = StrUtil.format(KeywordListener.KEYWORD_KEY_PREFIX, groupName);
        if (keys.length == 1 && keys[0] == null) {
            map = jedis.hgetAll(StrUtil.format(KeywordListener.KEYWORD_KEY_PREFIX, groupName));
        } else {
            for (String key : keys) {
                String count = jedis.hget(redisKey, key);
                map.put(key, count == null ? "0" : count);
            }
        }
        String s = map.entrySet().stream()
                .map(entry -> entry.getKey() + ": " + entry.getValue())
                .collect(Collectors.joining("\n"));
        return "关键词监控情况：\n" + s;
    }
}
